<?php

/**
 * 文档信息仓库
 * @author liuyw01 2016-1-13
 */

namespace common\repositories\myhtsq;

use common\repositories\BaseRepository;
use common\entities\myhtsq\SignDelyAttachementEntity;
use common\error\ErrorCode;
use common\repositories\common\MyscrmContractSyncDeleteDataRepository;
use common\support\StringHelper;

class SignDelyAttachementRepository extends BaseRepository {

    /**
     * 构造方法
     * @param unknown $config (optional)
     */
    public function __construct($config = []) {
        parent::__construct($config);
    }

    /**
     * 文档列表
     * @param string $contractId 合同id
     * @return array
     */
    public static function getAttachementListByContractId($contractId) {
        return SignDelyAttachementEntity::find()
                        ->where(['contract_id' => $contractId])
                        ->orderBy(['attachement_name' => SORT_ASC])
                        ->asArray()
                        ->all();
    }

    /**
     * 新增文档
     * @param $signDelyAttachement $signDelyAttachement
     * @return boolean|string 失败返回false，成功返回新增的文档Id
     */
    public static function addAttachement($signDelyAttachement) {
        try {
            $entity = new SignDelyAttachementEntity();
            $entity->setAttributes($signDelyAttachement->attributes);
            $entity->attachement_id = StringHelper::uuid();
            $result = $entity->save();
            if ($result === FALSE) {
                $error = $entity->firstErrorMessage;
                return self::setAndReturn(ErrorCode::ERR_QMYX_AGENCY_ACTIVE_RECORD_EXCEPTION, $error);
            } else {
                return $entity->primaryKey;
            }
        } catch (\Exception $ex) {
            return self::setAndReturn(ErrorCode::ERR_QMYX_AGENCY_ACTIVE_RECORD_EXCEPTION, (string) $ex);
        }
    }

    /**
     * 根据文件id,删除文件记录
     * @param string $attachement_id 文件id
     * @return boolean
     */
    public static function delAttachementById($attachement_id)
    {
        /** @var MyscrmContractSyncDeleteDataRepository $contractSyncDeleteDataRepository */
        $contractSyncDeleteDataRepository = \Yii::createObject(MyscrmContractSyncDeleteDataRepository::className());

        $deleteResult = SignDelyAttachementEntity::deleteAll(['attachement_id' => $attachement_id]);

        if ($deleteResult > 0) {
            $contractSyncDeleteDataRepository->add('myscrm_sign_achievement', 'achievement_id', $attachement_id);
        }

        return $deleteResult;
    }

}
